/**
 * @Title: OrderServiceImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年4月10日
 */
package com.fortune.rainshineservice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ProductModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.service.MessageModel;
import com.fortune.rainshinecommon.model.service.OrderDetailModel;
import com.fortune.rainshinecommon.model.service.OrderModel;
import com.fortune.rainshinecommon.model.service.StockModel;
import com.fortune.rainshinecommon.model.service.StockRecordsModel;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.util.StringUtil;
import com.fortune.rainshineservice.mapper.*;
import com.fortune.rainshineservice.service.MessageService;
import com.fortune.rainshineservice.service.OrderService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 张鑫
 * @ClassName: OrderServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @phone 17561783855
 * @date 2019年4月10日
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private StockRecordsMapper stockRecordsMapper;
    
    @Autowired
    private MessageService messageService;
    

    @Override
    public MsgModel list(ParmsModel parm) {
        try {
        	String shopId = "";
        	if(parm.getSearchKey()!= null && parm.getSearchKey().equals("shop_name")) {
        		shopId = parm.getSearchValue();
        	}else {
        		//登录账号的商铺
                ShopModel shopSelf = shopMapper.selectById(parm.getShopId());
                shopId = String.valueOf(shopSelf.getId());
        	}
            
            //封装页面搜索条件
            Wrapper<OrderModel> wrapper = new EntityWrapper<>();
            if (StringUtil.isNotBlank(parm.getSearchKey())) {
                wrapper.like(parm.getSearchKey(), parm.getSearchValue());
            }
            if (StringUtil.isNotBlank(parm.getBeginDate())) {
                wrapper.gt("create_time", parm.getBeginDate() + " 00:00:00");
            }
            if (StringUtil.isNotBlank(parm.getEndDate())) {
                wrapper.lt("create_time", parm.getEndDate() + " 23:59:59");
            }
            
            //判断若为采购订单
            if (parm.getType() == 1) {
            	
                wrapper.eq("shop_id", shopId);
            }
            //判断若为出货订单
            else if (parm.getType() == 2) {
                wrapper.eq("Shop_id_from", shopId);
            }
            
            Page<OrderModel> orderPage = new Page<>(parm.getPage(), parm.getLimit());
            List<OrderModel> list = Optional.ofNullable(orderMapper.selectPage(orderPage,
                    wrapper.orderBy("create_time", false))).orElse(Lists.newArrayList());
            int total = orderMapper.selectCount(wrapper);
            if (!list.isEmpty()) {
                for (OrderModel item : list) {
//                    User user = userMapper.selectById(item.getUserId());
                    ShopModel shop = shopMapper.selectById(item.getShopId());
                    ShopModel saleShop = shopMapper.selectById(item.getShopIdFrom());
                    User buyer = userMapper.selectById(shop.getManagerId());
                    item.setUserName(buyer.getNickName());
                    item.setUserPhone(buyer.getPhone());
                    if (parm.getType() == 1) {
                    	item.setShopName(saleShop.getShopName());
                    }else {
                    	item.setShopName(shop.getShopName());
                    }
                    
                    User saleUser = userMapper.selectById(saleShop.getManagerId());
                    item.setSaleUserName(saleUser.getNickName());
                    item.setSaleUserPhone(saleUser.getPhone());
                }
            }
            return new MsgModel(total, list);
        } catch (Exception e) {
            logger.error("list =====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @Override
    public List<OrderDetailModel> getDetailOrders(String orderCode) {
        List<OrderDetailModel> orders = Lists.newArrayList();
        try {
            Wrapper<OrderDetailModel> wrapper = new EntityWrapper<>();
            wrapper.eq("order_code", orderCode);
            wrapper.orderBy("create_time", true);
            orders = Optional.ofNullable(orderDetailMapper.selectList(wrapper)).orElse(Lists.newArrayList());
            if (!orders.isEmpty()) {
                orders.forEach(e->{
                    ProductModel product = productMapper.selectById(e.getProductId());
                    e.setProductName(product.getProductName());
                });
            }
        } catch (Exception e) {
            logger.error("getDetailOrders =====> {}", e);
        }
        return orders;
    }

    /**
     * @Title: confirmingAnOrder
     * @Description: 确认出货
     * @author zhangxin
     * @phone 17561783855
     * @date 2019年5月14日
     */
    @Override
    @Transactional
    public MsgModel confirmingAnOrder(OrderModel orderModel) {
//        try {
            //根据订单id获取订单详情
            OrderModel order = orderMapper.selectById(orderModel.getId());

            //判断订单是否存在
            if (order != null) {

                //获取购买者商铺信息
                ShopModel shopBuy = shopMapper.selectById(order.getShopId());

                //获取出售者(上级)店铺信息
                ShopModel shopSell = new ShopModel();
                shopSell.setManagerId(shopBuy.getMerchantsId());
                shopSell = shopMapper.selectOne(shopSell);

                //获取订单详情
                List<OrderDetailModel> details = this.getDetailOrders(order.getOrderCode());
                if (details != null) {
                    //先判断库存数量
                    for (OrderDetailModel o : details) {
                        //获取卖方该产品的库存信息
                        StockModel stock = new StockModel();
                        stock.setProductId(o.getProductId());
                        stock.setShopId(shopSell.getId());
                        StockModel stockSell = stockMapper.selectOne(stock);
                        StringBuilder productNames = new StringBuilder();
                        productNames.append("[");

                        //判断卖方是否存在该产品库存
                        if (stockSell == null) {
                            ProductModel product = productMapper.selectById(o.getProductId());
                            productNames.append(product.getProductName() + ";");
                            return new MsgModel("产品" + productNames.toString() + "]库存中不存在，无法确认下单，请先采购该产品！", ResultCode.FAILURE);
                        }

                        //判断卖方若现有库存数小于买方购买数，则该订单无法下单
                        if (stockSell.getProductAmount() < o.getQuantity()) {
                            ProductModel product = productMapper.selectById(o.getProductId());
                            productNames.append(product.getProductName() + ";");
                            return new MsgModel("产品" + productNames.toString() + "]库存数量不够，无法确认下单，请及时补货！", ResultCode.FAILURE);
                        }
                    }
                    //循环处理订单详情，处理销售方库存
                    for (OrderDetailModel item : details) {
                        //获取卖方该产品的库存信息
                        StockModel stock = new StockModel();
                        stock.setProductId(item.getProductId());
                        stock.setShopId(shopSell.getId());
                        StockModel stockSell = stockMapper.selectOne(stock);

                        stockSell.setProductAmount(stockSell.getProductAmount() - item.getQuantity());
                        if ((stockSell.getProductAmount() - item.getQuantity()) < stockSell.getWarningNum()) {
                        	//判断库存低于预警信息,则进行预警
                            MessageModel message = new MessageModel(shopSell.getManagerId(),3,item.getProductName());
                            messageService.addMessage(message);
                        }

                        //更新总库存
                        stockMapper.updateById(stockSell);
                        //插入库存记录
                        StockRecordsModel record = new StockRecordsModel(stockSell.getProductId(), shopSell.getId(), stockSell.getId(), item.getQuantity());
                        record.setType(2);
                        record.setCode(order.getOrderCode());
                        record.setCreateId(orderModel.getUser().getUserId());
                        record.setUpdateId(orderModel.getUser().getUserId());
                        stockRecordsMapper.insert(record);
                    }
                }
                order.setOrderStatus((byte) 2);
                order.setUpdateTime(new Date());
                order.setUpdateId(orderModel.getUser().getUserId());
                orderMapper.updateById(order);
                
                //像卖方插入采购信息
                MessageModel message = new MessageModel(shopBuy.getManagerId(),2,shopSell.getShopName());
                messageService.addMessage(message);
            } else {
                return new MsgModel(ResultCode.FAILURE, "该订单不存在");
            }
            return new MsgModel(ResultCode.SUCCESS, "订单确认下单成功！");
//        } catch (Exception e) {
//            logger.error("confirmingAnOrder =====> {}", e);
//            return new MsgModel("确认出货异常", ResultCode.FAILURE);
//        }
    }

    @Override
    public MsgModel getOrderDetail(OrderModel orderModel) {
        try {
            OrderModel om = orderMapper.selectByOrderCode(orderModel.getOrderCode());
            om.setOrderList(getDetailOrders(orderModel.getOrderCode()));
            User user = userMapper.selectById(om.getUserId());
            ShopModel shop = shopMapper.selectById(om.getShopId());
            om.setUserName(user != null ? user.getNickName() : null);
            om.setUserPhone(user != null ? user.getPhone() : null);
            om.setShopName(shop != null ? shop.getShopName() : null);
            ShopModel saleShop = shopMapper.selectById(om.getShopIdFrom());
            User saleUser = userMapper.selectById(saleShop.getManagerId());
            om.setSaleUserName(saleUser.getNickName());
            om.setSaleUserPhone(saleUser.getPhone());
            return new MsgModel(ResultCode.SUCCESS, om);
        } catch (Exception e) {
            logger.error("getOrderDetail ======> {}", e);
            return new MsgModel("获取订单详情失败！", ResultCode.FAILURE);
        }
    }

    /**
     * @Title: receivingAnOrder
     * @Description: 买方确认收货
     * @author zhangxin
     * @phone 17561783855
     * @date 2019年5月14日
     */
    @Override
    @Transactional
    public MsgModel receivingAnOrder(OrderModel model) {
//        try {
            //根据订单id获取订单详情
            OrderModel order = orderMapper.selectById(model.getId());

            //判断订单是否存在
            if (order != null) {

                //获取购买者商铺信息
                ShopModel shopBuy = shopMapper.selectById(order.getShopId());

                //获取订单详情
                List<OrderDetailModel> details = this.getDetailOrders(order.getOrderCode());
                if (details != null) {

                    for (OrderDetailModel item : details) {
                        //获取买方该产品的库存
                        StockModel stock2 = new StockModel();
                        stock2.setProductId(item.getProductId());
                        stock2.setShopId(shopBuy.getId());
                        StockModel stockBuy = stockMapper.selectOne(stock2);

                        StockRecordsModel recordBuy;
                        //判断若买方已经存在该产品库存，则更新库存信息
                        if (stockBuy != null) {
                            stockBuy.setProductAmount(stockBuy.getProductAmount() + item.getQuantity());
                            stockMapper.updateById(stockBuy);
                            recordBuy = new StockRecordsModel(stockBuy.getProductId(), stockBuy.getShopId(), stockBuy.getId(), item.getQuantity());
                        } else {//判断若买方不存在该产品库存信息，则新建买方的该产品库存信息
                            StockModel stock3 = new StockModel(item.getProductId(), shopBuy.getId(), item.getQuantity(), 0);
                            //插入库存信息
                            stockMapper.insert(stock3);
                            //获取刚插入的库存信息详情
                            StockModel stock4 = stockMapper.selectOne(stock3);
                            recordBuy = new StockRecordsModel(stock4.getProductId(), stock4.getShopId(), stock4.getId(), item.getQuantity());
                        }
                        //将该条信息插入库存记录
                        recordBuy.setType(1);
                        recordBuy.setCode(order.getOrderCode());
                        recordBuy.setCreateId(model.getUser().getUserId());
                        recordBuy.setUpdateId(model.getUser().getUserId());
                        stockRecordsMapper.insert(recordBuy);
                    }
                }
                order.setOrderStatus((byte) 3);
                order.setUpdateTime(new Date());
                order.setUpdateId(model.getUser().getUserId());
                orderMapper.updateById(order);
            } else {
                return new MsgModel(ResultCode.FAILURE, "该订单不存在");
            }
//        } catch (Exception e) {
//            logger.error("receivingAnOrder ======> {}", e);
//        }
        return new MsgModel(ResultCode.SUCCESS, "订单确认收货成功！");
    }

    @Override
    public OrderModel getByOrderCode(String orderCode) {
        return orderMapper.selectByOrderCode(orderCode);
    }

    @Override
    @Transactional
    public MsgModel cancelOrder(OrderModel orderModel) {
        try {
            //获取订单详情
            OrderModel order = orderMapper.selectById(orderModel.getId());
            if (order != null) {
                if (order.getOrderStatus().intValue() != 1) {
                    return new MsgModel("订单状态异常，请刷新页面", ResultCode.FAILURE);
                }
                Wrapper<OrderModel> wrapper = new EntityWrapper<>();
                wrapper.eq("id", orderModel.getId());
                orderMapper.updateForSet("order_status = " + orderModel.getOrderStatus(), wrapper);
            } else {
                return new MsgModel("取消失败，该订单不存在！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("OrderServiceImpl cancelOrder ======> {}", e);
            return new MsgModel("取消失败，系统异常！", ResultCode.FAILURE);
        }
        return new MsgModel("订单取消成功！", ResultCode.SUCCESS);
    }
}